#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
激光打刻辅助系统
功能：根据用户设置生成序列号并保存到shuru.txt文件
作者：擎天小福
"""

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
from pathlib import Path

class SequenceGenerator:
    def __init__(self, root):
        self.root = root
        # 文件路径
        self.qr_file_path = os.path.join(os.getcwd(), "shuchu_tiaoma.txt")
        self.text_file_path = os.path.join(os.getcwd(), "shuchu_wenben.txt")
        self.shuru_file_path = os.path.join(os.getcwd(), "shuru.txt")
        # 文件监控相关
        self.last_qr_mtime = 0
        self.last_text_mtime = 0
        # 完成提醒标志，避免重复弹窗
        self.completion_dialog_shown = False
        self.setup_window()
        self.setup_styles()
        self.create_widgets()
        # 启动文件监控
        self.start_file_monitoring()
        
    def setup_window(self):
        """设置主窗口属性"""
        self.root.title("激光打刻辅助软件 v1.0.0")
        self.root.geometry("1000x650")
        self.root.resizable(True, True)
        self.root.minsize(900, 600)  # 设置最小窗口大小
        
        # 设置窗口居中
        self.center_window()
        
        # 设置主题色彩
        self.root.configure(bg='#2c3e50')
        
        # 设置样式
        self.setup_styles()
        
    def center_window(self):
        """将窗口居中显示"""
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f'{width}x{height}+{x}+{y}')
        
    def setup_styles(self):
        """设置ttk样式主题"""
        self.style = ttk.Style()
        self.style.theme_use('clam')
        
        # 配置样式
        self.style.configure('Title.TLabel', 
                           font=('Microsoft YaHei', 16, 'bold'),
                           foreground='#ecf0f1',
                           background='#2c3e50')
        
        self.style.configure('Subtitle.TLabel',
                           font=('Microsoft YaHei', 10),
                           foreground='#bdc3c7',
                           background='#2c3e50')
        
        self.style.configure('Custom.TEntry',
                           font=('Microsoft YaHei', 10),
                           fieldbackground='#ecf0f1',
                           borderwidth=2,
                           relief='solid')
        
        self.style.configure('Generate.TButton',
                           font=('Microsoft YaHei', 14, 'bold'),
                           foreground='white',
                           background='#e74c3c',
                           borderwidth=2,
                           relief='raised',
                           focuscolor='none')
        
        self.style.map('Generate.TButton',
                      background=[('active', '#c0392b'),
                                ('pressed', '#a93226')],
                      relief=[('pressed', 'sunken')])
        
        self.style.configure('Custom.TButton',
                           font=('Microsoft YaHei', 11),
                           foreground='white',
                           background='#3498db',
                           borderwidth=1,
                           focuscolor='none')
        
        self.style.map('Custom.TButton',
                      background=[('active', '#2980b9'),
                                ('pressed', '#21618c')])
        
    def create_widgets(self):
        """创建所有GUI组件"""
        # 主容器
        main_frame = tk.Frame(self.root, bg='#2c3e50', padx=25, pady=20)
        main_frame.pack(fill='both', expand=True)
        
        # 标题区域
        header_frame = tk.Frame(main_frame, bg='#2c3e50')
        header_frame.pack(fill='x', pady=(0, 25))
        
        title_label = ttk.Label(header_frame, text="🚀 激光打刻辅助系统", style='Title.TLabel')
        title_label.pack()
        
        subtitle_label = ttk.Label(header_frame, text="快速生成连续序列号，支持自定义格式", style='Subtitle.TLabel')
        subtitle_label.pack(pady=(5, 0))
        
        # 主内容区域 - 左右分栏布局
        content_frame = tk.Frame(main_frame, bg='#2c3e50')
        content_frame.pack(fill='both', expand=True)
        
        # 左侧区域 - 输入和预览
        left_frame = tk.Frame(content_frame, bg='#2c3e50')
        left_frame.pack(side='left', fill='both', expand=True, padx=(0, 15))
        
        # 输入区域
        input_frame = tk.Frame(left_frame, bg='#34495e', relief='raised', bd=2)
        input_frame.pack(fill='x', pady=(0, 15))
        
        input_inner = tk.Frame(input_frame, bg='#34495e', padx=20, pady=20)
        input_inner.pack(fill='both', expand=True)
        
        input_title = ttk.Label(input_inner, text="⚙️ 参数设置", style='Subtitle.TLabel')
        input_title.pack(anchor='w', pady=(0, 15))
        
        # 创建输入行
        self.create_input_row(input_inner, "固定文本设置:", "fixed_text", "100969DHT30-1600024250801", 0)
        self.create_input_row(input_inner, "开始序列号:", "start_num", "0001", 1)
        self.create_input_row(input_inner, "最大序列号:", "max_num", "9999", 2)
        self.create_input_row(input_inner, "序号增量:", "increment", "1", 3)
        
        # 预览区域
        preview_frame = tk.Frame(left_frame, bg='#34495e', relief='raised', bd=2)
        preview_frame.pack(fill='both', expand=True)
        
        preview_inner = tk.Frame(preview_frame, bg='#34495e', padx=20, pady=20)
        preview_inner.pack(fill='both', expand=True)
        
        preview_label = ttk.Label(preview_inner, text="📋 预览效果", style='Subtitle.TLabel')
        preview_label.pack(anchor='w', pady=(0, 10))
        
        self.preview_text = tk.Text(preview_inner, height=6, 
                                   font=('Consolas', 10),
                                   bg='#2c3e50', fg='#ecf0f1',
                                   relief='solid', bd=1,
                                   state='disabled')
        self.preview_text.pack(fill='both', expand=True)
        
        # 右侧区域 - 功能模块
        right_frame = tk.Frame(content_frame, bg='#2c3e50')
        right_frame.pack(side='right', fill='both', expand=True)
        
        # 文本对比显示框
        compare_frame = tk.Frame(right_frame, bg='#34495e', relief='raised', bd=2)
        compare_frame.pack(fill='x', pady=(0, 15))
        
        compare_inner = tk.Frame(compare_frame, bg='#34495e', padx=20, pady=20)
        compare_inner.pack(fill='both', expand=True)
        
        compare_label = ttk.Label(compare_inner, text="📊 二维码和文本对比", style='Subtitle.TLabel')
        compare_label.pack(anchor='w', pady=(0, 10))
        
        self.compare_status = tk.Label(compare_inner, text="等待对比", 
                                     font=('Microsoft YaHei', 14, 'bold'),
                                     bg='#95a5a6', fg='white',
                                     relief='solid', bd=2, pady=15)
        self.compare_status.pack(fill='x')
        
        # 最后打刻显示框（条码）
        last_print_qr_frame = tk.Frame(right_frame, bg='#34495e', relief='raised', bd=2)
        last_print_qr_frame.pack(fill='x', pady=(0, 15))
        
        last_print_qr_inner = tk.Frame(last_print_qr_frame, bg='#34495e', padx=20, pady=20)
        last_print_qr_inner.pack(fill='both', expand=True)
        
        last_print_qr_label = ttk.Label(last_print_qr_inner, text="🎯 最后打刻显示（条码）", style='Subtitle.TLabel')
        last_print_qr_label.pack(anchor='w', pady=(0, 10))
        
        self.last_print_qr_text = tk.Text(last_print_qr_inner, height=3,
                                         font=('Consolas', 12),
                                         bg='#2c3e50', fg='#ecf0f1',
                                         relief='solid', bd=1,
                                         state='disabled')
        self.last_print_qr_text.pack(fill='both', expand=True)
        
        # 最后打刻显示框（文本）
        last_print_text_frame = tk.Frame(right_frame, bg='#34495e', relief='raised', bd=2)
        last_print_text_frame.pack(fill='both', expand=True)
        
        last_print_text_inner = tk.Frame(last_print_text_frame, bg='#34495e', padx=20, pady=20)
        last_print_text_inner.pack(fill='both', expand=True)
        
        last_print_text_label = ttk.Label(last_print_text_inner, text="📝 最后打刻显示（文本）", style='Subtitle.TLabel')
        last_print_text_label.pack(anchor='w', pady=(0, 10))
        
        self.last_print_text_text = tk.Text(last_print_text_inner, height=3,
                                           font=('Consolas', 12),
                                           bg='#2c3e50', fg='#ecf0f1',
                                           relief='solid', bd=1,
                                           state='disabled')
        self.last_print_text_text.pack(fill='both', expand=True)
        
        # 底部区域 - 按钮和状态栏
        bottom_frame = tk.Frame(main_frame, bg='#2c3e50')
        bottom_frame.pack(fill='x', pady=(25, 0))
        
        # 按钮区域
        button_frame = tk.Frame(bottom_frame, bg='#2c3e50')
        button_frame.pack(fill='x', pady=(0, 15))
        
        # 按钮居中布局
        button_center_frame = tk.Frame(button_frame, bg='#2c3e50')
        button_center_frame.pack()
        
        # 预览按钮
        preview_btn = ttk.Button(button_center_frame, text="🔍 预览", 
                               command=self.preview_sequence,
                               style='Custom.TButton')
        preview_btn.pack(side='left', padx=(0, 10))
        
        # 生成按钮（主要按钮）
        generate_btn = ttk.Button(button_center_frame, text="⚡ 生成序列号", 
                                command=self.generate_sequence,
                                style='Generate.TButton')
        generate_btn.pack(side='left', padx=(0, 10))
        
        # 清空shuru文件按钮
        clear_btn = ttk.Button(button_center_frame, text="🗑️ 清空shuru文件", 
                             command=self.clear_file,
                             style='Custom.TButton')
        clear_btn.pack(side='left', padx=(0, 10))
        
        # 清空shuchu文件按钮
        clear_shuchu_btn = ttk.Button(button_center_frame, text="🗑️ 清空shuchu文件", 
                                    command=self.clear_shuchu_files,
                                    style='Custom.TButton')
        clear_shuchu_btn.pack(side='left')
        
        # 状态栏
        status_frame = tk.Frame(bottom_frame, bg='#34495e', relief='sunken', bd=1)
        status_frame.pack(fill='x')
        
        self.status_var = tk.StringVar(value="就绪")
        status_label = ttk.Label(status_frame, textvariable=self.status_var, 
                               style='Subtitle.TLabel')
        status_label.pack(pady=8)
        
        # 绑定实时预览事件
        for entry in [self.fixed_text_entry, self.start_num_entry, 
                     self.max_num_entry, self.increment_entry]:
            entry.bind('<KeyRelease>', self.on_input_change)
            
    def create_input_row(self, parent, label_text, var_name, default_value, row):
        """创建输入行组件"""
        row_frame = tk.Frame(parent, bg='#34495e')
        row_frame.pack(fill='x', pady=8)
        
        # 标签 - 使用固定宽度确保对齐
        label = ttk.Label(row_frame, text=label_text, style='Subtitle.TLabel', width=12)
        label.pack(side='left', anchor='w')
        
        # 输入框
        entry = ttk.Entry(row_frame, style='Custom.TEntry', width=30)
        entry.pack(side='left', anchor='w', padx=(10, 0))  # 减少左边距，因为标签已固定宽度
        entry.insert(0, default_value)
        
        # 保存引用
        setattr(self, f"{var_name}_entry", entry)
        
    def on_input_change(self, event=None):
        """输入框内容改变时的回调"""
        # 可以在这里添加实时验证逻辑
        pass
        
    def preview_sequence(self):
        """预览序列号生成效果"""
        try:
            fixed_text = self.fixed_text_entry.get().strip()
            start_num = int(self.start_num_entry.get().strip())
            max_num = int(self.max_num_entry.get().strip())
            increment = int(self.increment_entry.get().strip())
            
            if start_num > max_num:
                messagebox.showerror("错误", "开始序列号不能大于最大序列号！")
                return
                
            if increment <= 0:
                messagebox.showerror("错误", "序号增量必须大于0！")
                return
            
            # 获取开始序列号的位数
            start_str = self.start_num_entry.get().strip()
            num_digits = len(start_str)
            
            # 生成预览（最多显示5行）
            preview_lines = []
            current_num = start_num
            count = 0
            
            while current_num <= max_num and count < 5:
                formatted_num = str(current_num).zfill(num_digits)
                sequence = f"{fixed_text}{formatted_num}"
                preview_lines.append(sequence)
                current_num += increment
                count += 1
                
            if current_num <= max_num:
                preview_lines.append("...")
                
            # 更新预览文本
            self.preview_text.config(state='normal')
            self.preview_text.delete(1.0, tk.END)
            self.preview_text.insert(1.0, "\n".join(preview_lines))
            self.preview_text.config(state='disabled')
            
            # 计算总数量
            total_count = (max_num - start_num) // increment + 1
            self.status_var.set(f"预览完成 - 将生成 {total_count} 个序列号")
            
        except ValueError:
            messagebox.showerror("错误", "请输入有效的数字！")
        except Exception as e:
            messagebox.showerror("错误", f"预览失败：{str(e)}")
            
    def check_duplicate_sequences(self, fixed_text, start_num, max_num, increment, num_digits):
        """检查即将生成的序列号是否与现有文件中的数据重复"""
        try:
            # 读取现有的shuru.txt文件内容
            output_file = os.path.join(os.getcwd(), "shuru.txt")
            existing_sequences = set()
            
            try:
                with open(output_file, 'r', encoding='utf-8') as f:
                    for line in f:
                        line = line.strip()
                        if line:
                            existing_sequences.add(line)
            except FileNotFoundError:
                # 文件不存在，没有重复数据
                return False, []
            
            # 生成即将创建的序列号列表
            new_sequences = []
            current_num = start_num
            while current_num <= max_num:
                formatted_num = str(current_num).zfill(num_digits)
                sequence = f"{fixed_text}{formatted_num}"
                new_sequences.append(sequence)
                current_num += increment
            
            # 检查重复
            duplicates = []
            for seq in new_sequences:
                if seq in existing_sequences:
                    duplicates.append(seq)
            
            return len(duplicates) > 0, duplicates
            
        except Exception as e:
            messagebox.showerror("错误", f"检查重复数据时发生错误：{str(e)}")
            return True, []  # 发生错误时，阻止生成
    
    def generate_sequence(self):
        """生成序列号并保存到文件"""
        try:
            fixed_text = self.fixed_text_entry.get().strip()
            start_num = int(self.start_num_entry.get().strip())
            max_num = int(self.max_num_entry.get().strip())
            increment = int(self.increment_entry.get().strip())
            
            # 验证输入
            if not fixed_text:
                messagebox.showerror("错误", "固定文本不能为空！")
                return
                
            if start_num > max_num:
                messagebox.showerror("错误", "开始序列号不能大于最大序列号！")
                return
                
            if increment <= 0:
                messagebox.showerror("错误", "序号增量必须大于0！")
                return
            
            # 获取开始序列号的位数
            start_str = self.start_num_entry.get().strip()
            num_digits = len(start_str)
            
            # 检查重复数据
            has_duplicates, duplicate_list = self.check_duplicate_sequences(fixed_text, start_num, max_num, increment, num_digits)
            if has_duplicates:
                duplicate_count = len(duplicate_list)
                # 显示前5个重复的序列号作为示例
                sample_duplicates = duplicate_list[:5]
                sample_text = "\n".join(sample_duplicates)
                if duplicate_count > 5:
                    sample_text += f"\n... 还有 {duplicate_count - 5} 个重复项"
                
                messagebox.showerror(
                    "数据重复警告", 
                    f"检测到 {duplicate_count} 个重复的序列号！\n\n"
                    f"重复的序列号示例：\n{sample_text}\n\n"
                    f"请修改参数设置或清空shuru.txt文件后重试。"
                )
                self.status_var.set(f"❌ 检测到 {duplicate_count} 个重复序列号，生成已停止")
                return
            
            # 计算总数量
            total_count = (max_num - start_num) // increment + 1
            
            # 检查文件是否存在内容
            output_file = os.path.join(os.getcwd(), "shuru.txt")
            file_has_content = False
            try:
                with open(output_file, 'r', encoding='utf-8') as f:
                    content = f.read().strip()
                    file_has_content = len(content) > 0
            except FileNotFoundError:
                file_has_content = False
            
            # 如果文件有内容，询问用户是否追加
            write_mode = 'w'
            if file_has_content:
                choice = messagebox.askyesnocancel(
                    "文件操作选择",
                    f"shuru.txt 文件中已有内容。\n\n"
                    f"点击'是'：追加到现有内容后面\n"
                    f"点击'否'：覆盖现有内容\n"
                    f"点击'取消'：取消操作\n\n"
                    f"将生成 {total_count} 个序列号"
                )
                if choice is None:  # 用户点击取消
                    return
                elif choice:  # 用户点击是（追加）
                    write_mode = 'a'
                else:  # 用户点击否（覆盖）
                    write_mode = 'w'
            else:
                # 文件为空或不存在，直接确认生成
                result = messagebox.askyesno("确认生成", 
                                           f"将生成 {total_count} 个序列号到 shuru.txt 文件\n\n"
                                           f"示例：{fixed_text}{str(start_num).zfill(num_digits)}\n"
                                           f"是否继续？")
                if not result:
                    return
            
            # 生成序列号
            self.status_var.set("正在生成序列号...")
            self.root.update()
            
            with open(output_file, write_mode, encoding='utf-8') as f:
                current_num = start_num
                generated_count = 0
                
                while current_num <= max_num:
                    formatted_num = str(current_num).zfill(num_digits)
                    sequence = f"{fixed_text}{formatted_num}"
                    f.write(sequence + "\n")
                    current_num += increment
                    generated_count += 1
                    
                    # 更新进度
                    if generated_count % 1000 == 0:
                        self.status_var.set(f"已生成 {generated_count} 个序列号...")
                        self.root.update()
            
            mode_text = "追加" if write_mode == 'a' else "生成"
            self.status_var.set(f"✅ 成功{mode_text} {generated_count} 个序列号到 shuru.txt")
            messagebox.showinfo("成功", f"已成功{mode_text} {generated_count} 个序列号到 shuru.txt 文件！")
            
        except ValueError:
            messagebox.showerror("错误", "请输入有效的数字！")
        except Exception as e:
            messagebox.showerror("错误", f"生成失败：{str(e)}")
            self.status_var.set("生成失败")
            
    def clear_file(self):
        """清空shuru.txt文件"""
        result = messagebox.askyesno("确认清空", "确定要清空 shuru.txt 文件吗？")
        if result:
            try:
                output_file = os.path.join(os.getcwd(), "shuru.txt")
                with open(output_file, 'w', encoding='utf-8') as f:
                    f.write('')
                self.status_var.set("✅ 文件已清空")
                messagebox.showinfo("成功", "shuru.txt 文件已清空！")
            except Exception as e:
                messagebox.showerror("错误", f"清空文件时发生错误：{str(e)}")
                
    def clear_shuchu_files(self):
        """清空shuchu输出文件"""
        result = messagebox.askyesno("确认清空", "确定要清空 shuchu_tiaoma.txt 和 shuchu_wenben.txt 文件吗？")
        if result:
            try:
                # 清空二维码输出文件
                with open(self.qr_file_path, 'w', encoding='utf-8') as f:
                    f.write('')
                # 清空文本输出文件
                with open(self.text_file_path, 'w', encoding='utf-8') as f:
                    f.write('')
                
                # 重置文件监控时间戳
                self.last_qr_mtime = 0
                self.last_text_mtime = 0
                
                # 重置显示
                self.compare_status.config(text="等待对比", bg='#95a5a6')
                
                # 清空条码显示框
                self.last_print_qr_text.config(state='normal')
                self.last_print_qr_text.delete('1.0', tk.END)
                self.last_print_qr_text.insert('1.0', "暂无数据")
                self.last_print_qr_text.config(state='disabled')
                
                # 清空文本显示框
                self.last_print_text_text.config(state='normal')
                self.last_print_text_text.delete('1.0', tk.END)
                self.last_print_text_text.insert('1.0', "暂无数据")
                self.last_print_text_text.config(state='disabled')
                
                self.status_var.set("✅ shuchu文件已清空")
                messagebox.showinfo("成功", "shuchu_tiaoma.txt 和 shuchu_wenben.txt 文件已清空！")
            except Exception as e:
                messagebox.showerror("错误", f"清空shuchu文件时发生错误：{str(e)}")
            
    def start_file_monitoring(self):
        """启动文件监控"""
        self.check_file_changes()
        # 每500毫秒检查一次文件变化
        self.root.after(500, self.start_file_monitoring)
    
    def check_file_changes(self):
        """检查文件变化"""
        try:
            # 检查二维码文件
            if os.path.exists(self.qr_file_path):
                qr_mtime = os.path.getmtime(self.qr_file_path)
                if qr_mtime != self.last_qr_mtime:
                    self.last_qr_mtime = qr_mtime
                    self.update_last_print_qr_display()
                    self.compare_files()
            
            # 检查文本文件
            if os.path.exists(self.text_file_path):
                text_mtime = os.path.getmtime(self.text_file_path)
                if text_mtime != self.last_text_mtime:
                    self.last_text_mtime = text_mtime
                    self.update_last_print_text_display()
                    self.compare_files()
        except Exception as e:
            print(f"文件监控错误: {e}")
    
    def read_file_content(self, file_path):
        """读取文件内容"""
        try:
            if os.path.exists(file_path):
                with open(file_path, 'r', encoding='utf-8') as f:
                    return f.read().strip()
            return ""
        except Exception as e:
            print(f"读取文件错误 {file_path}: {e}")
            return ""
    
    def compare_files(self):
        """对比两个文件内容（只对比序列号部分）"""
        qr_content = self.read_file_content(self.qr_file_path)
        text_content = self.read_file_content(self.text_file_path)
        
        if not qr_content and not text_content:
            self.compare_status.config(text="等待对比", bg='#95a5a6')
            return
        
        # 提取两个文件中的序列号进行对比
        qr_sequences = self.extract_sequences(qr_content)
        text_sequences = self.extract_sequences(text_content)
        
        if qr_sequences == text_sequences:
            self.compare_status.config(text="✅ 合格", bg='#27ae60')
        else:
            self.compare_status.config(text="❌ 文本对比不一致", bg='#e74c3c')
            # 弹出对话框显示差异
            self.show_difference_dialog(qr_sequences, text_sequences)
    
    def extract_sequences(self, content):
        """从文件内容中提取所有序列号"""
        import re
        if not content:
            return []
        
        # 获取当前设置的固定文本
        current_fixed_text = self.get_current_fixed_text()
        
        # 动态构建正则表达式，转义特殊字符
        escaped_text = re.escape(current_fixed_text)
        pattern = escaped_text + r'\d+'
        
        # 使用正则表达式提取所有当前固定文本格式的序列号
        sequences = re.findall(pattern, content)
        return sequences
    
    def show_difference_dialog(self, qr_sequences, text_sequences):
        """显示序列号差异对话框"""
        diff_window = tk.Toplevel(self.root)
        diff_window.title("序列号对比差异")
        diff_window.geometry("600x400")
        diff_window.configure(bg='#2c3e50')
        
        # 标题
        title_label = tk.Label(diff_window, text="序列号对比不一致", 
                              font=('Microsoft YaHei', 14, 'bold'),
                              bg='#2c3e50', fg='#e74c3c')
        title_label.pack(pady=10)
        
        # 创建对比框架
        compare_frame = tk.Frame(diff_window, bg='#2c3e50')
        compare_frame.pack(fill='both', expand=True, padx=20, pady=10)
        
        # 二维码文件序列号
        qr_label = tk.Label(compare_frame, text="二维码文件序列号:", 
                           font=('Microsoft YaHei', 10, 'bold'),
                           bg='#2c3e50', fg='#ecf0f1')
        qr_label.pack(anchor='w')
        
        qr_text = tk.Text(compare_frame, height=8, width=70,
                         font=('Consolas', 9),
                         bg='#34495e', fg='#ecf0f1')
        qr_text.pack(fill='x', pady=(5, 10))
        qr_text.insert('1.0', '\n'.join(qr_sequences) if qr_sequences else '无序列号')
        qr_text.config(state='disabled')
        
        # 文本文件序列号
        text_label = tk.Label(compare_frame, text="文本文件序列号:", 
                             font=('Microsoft YaHei', 10, 'bold'),
                             bg='#2c3e50', fg='#ecf0f1')
        text_label.pack(anchor='w')
        
        text_text = tk.Text(compare_frame, height=8, width=70,
                           font=('Consolas', 9),
                           bg='#34495e', fg='#ecf0f1')
        text_text.pack(fill='x', pady=(5, 10))
        text_text.insert('1.0', '\n'.join(text_sequences) if text_sequences else '无序列号')
        text_text.config(state='disabled')
        
        # 关闭按钮
        close_btn = tk.Button(diff_window, text="关闭", 
                             command=diff_window.destroy,
                             font=('Microsoft YaHei', 10),
                             bg='#3498db', fg='white',
                             relief='flat', padx=20, pady=5)
        close_btn.pack(pady=10)
    
    def get_current_fixed_text(self):
        """获取当前设置的固定文本"""
        try:
            return self.fixed_text_entry.get().strip()
        except:
            return "DAED-jianhao"  # 默认值
    
    def update_last_print_qr_display(self):
        """更新最后打刻显示（条码）"""
        try:
            content = self.read_file_content(self.qr_file_path)
            if content:
                # 解析最后一条记录，只提取序列号
                lines = content.strip().split('\n')
                display_text = "暂无数据"
                
                # 获取当前设置的固定文本
                current_fixed_text = self.get_current_fixed_text()
                
                # 从后往前查找包含当前固定文本格式的序列号
                for line in reversed(lines):
                    line = line.strip()
                    # 查找包含当前固定文本格式的序列号
                    if current_fixed_text in line:
                        # 提取序列号部分，去掉可能的前后缀
                        import re
                        # 动态构建正则表达式，转义特殊字符
                        escaped_text = re.escape(current_fixed_text)
                        pattern = escaped_text + r'\d+'
                        match = re.search(pattern, line)
                        if match:
                            display_text = match.group(0)
                            break
                
                # 更新显示
                self.last_print_qr_text.config(state='normal')
                self.last_print_qr_text.delete('1.0', tk.END)
                self.last_print_qr_text.insert('1.0', display_text)
                self.last_print_qr_text.config(state='disabled')
                
                # 检查是否完成所有序列号的打刻
                self.check_completion_status(display_text)
            else:
                self.last_print_qr_text.config(state='normal')
                self.last_print_qr_text.delete('1.0', tk.END)
                self.last_print_qr_text.insert('1.0', "暂无数据")
                self.last_print_qr_text.config(state='disabled')
                # 重置完成标志
                self.completion_dialog_shown = False
        except Exception as e:
            print(f"更新最后打刻显示（条码）错误: {e}")
    
    def update_last_print_text_display(self):
        """更新最后打刻显示（文本）"""
        try:
            content = self.read_file_content(self.text_file_path)
            if content:
                # 解析最后一条记录，只提取序列号
                lines = content.strip().split('\n')
                display_text = "暂无数据"
                
                # 获取当前设置的固定文本
                current_fixed_text = self.get_current_fixed_text()
                
                # 从后往前查找包含当前固定文本格式的序列号
                for line in reversed(lines):
                    line = line.strip()
                    # 查找包含当前固定文本格式的序列号
                    if current_fixed_text in line:
                        # 提取序列号部分，去掉可能的前后缀
                        import re
                        # 动态构建正则表达式，转义特殊字符
                        escaped_text = re.escape(current_fixed_text)
                        pattern = escaped_text + r'\d+'
                        match = re.search(pattern, line)
                        if match:
                            display_text = match.group(0)
                            break
                
                # 更新显示
                self.last_print_text_text.config(state='normal')
                self.last_print_text_text.delete('1.0', tk.END)
                self.last_print_text_text.insert('1.0', display_text)
                self.last_print_text_text.config(state='disabled')
                
                # 检查是否完成所有序列号的打刻
                self.check_completion_status(display_text)
            else:
                self.last_print_text_text.config(state='normal')
                self.last_print_text_text.delete('1.0', tk.END)
                self.last_print_text_text.insert('1.0', "暂无数据")
                self.last_print_text_text.config(state='disabled')
                # 重置完成标志
                self.completion_dialog_shown = False
        except Exception as e:
            print(f"更新最后打刻显示（文本）错误: {e}")
    
    def get_last_sequence_from_shuru(self):
        """获取shuru.txt文件中的最后一行序列号"""
        try:
            content = self.read_file_content(self.shuru_file_path)
            if content:
                lines = content.strip().split('\n')
                # 获取当前设置的固定文本
                current_fixed_text = self.get_current_fixed_text()
                
                # 从后往前查找包含当前固定文本格式的序列号
                for line in reversed(lines):
                    line = line.strip()
                    if line and current_fixed_text in line:
                        # 提取序列号部分
                        import re
                        # 动态构建正则表达式，转义特殊字符
                        escaped_text = re.escape(current_fixed_text)
                        pattern = escaped_text + r'\d+'
                        match = re.search(pattern, line)
                        if match:
                            return match.group(0)
            return None
        except Exception as e:
            print(f"读取shuru.txt最后序列号错误: {e}")
            return None
    
    def check_completion_status(self, current_sequence):
        """检查是否已完成所有序列号的打刻"""
        if not current_sequence or current_sequence == "暂无数据":
            return
        
        # 获取shuru.txt中的最后一行序列号
        last_shuru_sequence = self.get_last_sequence_from_shuru()
        
        if last_shuru_sequence and current_sequence == last_shuru_sequence:
            # 如果还没有显示过完成对话框，则显示
            if not self.completion_dialog_shown:
                self.show_completion_dialog()
                self.completion_dialog_shown = True
        else:
            # 如果序列号不一致，重置标志
            self.completion_dialog_shown = False
    
    def show_completion_dialog(self):
        """显示完成提醒对话框"""
        # 创建顶级窗口
        completion_window = tk.Toplevel(self.root)
        completion_window.title("打刻完成提醒")
        completion_window.geometry("600x300")
        completion_window.configure(bg='#e74c3c')  # 红色背景
        completion_window.resizable(False, False)
        
        # 设置窗口居中
        completion_window.transient(self.root)
        completion_window.grab_set()
        
        # 计算居中位置
        completion_window.update_idletasks()
        x = (completion_window.winfo_screenwidth() // 2) - (600 // 2)
        y = (completion_window.winfo_screenheight() // 2) - (300 // 2)
        completion_window.geometry(f'600x300+{x}+{y}')
        
        # 主容器
        main_frame = tk.Frame(completion_window, bg='#e74c3c', padx=30, pady=30)
        main_frame.pack(fill='both', expand=True)
        
        # 标题
        title_label = tk.Label(main_frame, 
                              text="⚠️ 生成的号码已打刻完毕！", 
                              font=('Microsoft YaHei', 18, 'bold'),
                              bg='#e74c3c', fg='white')
        title_label.pack(pady=(0, 20))
        
        # 提醒内容
        content_text = """请执行以下操作：

1. 清空shuru/shuchu文本文件
2. 将Ezcad软件中的变量设置中的文本行数改为1
   （二维码和条码都需要更改）"""
        
        content_label = tk.Label(main_frame, 
                                text=content_text,
                                font=('Microsoft YaHei', 14),
                                bg='#e74c3c', fg='white',
                                justify='left')
        content_label.pack(pady=(0, 30))
        
        # 按钮框架
        button_frame = tk.Frame(main_frame, bg='#e74c3c')
        button_frame.pack()
        
        # 确定按钮
        ok_button = tk.Button(button_frame, 
                             text="我知道了",
                             font=('Microsoft YaHei', 12, 'bold'),
                             bg='white', fg='#e74c3c',
                             relief='flat', padx=30, pady=10,
                             command=completion_window.destroy)
        ok_button.pack(side='left', padx=(0, 10))
        
        # 清空文件按钮
        clear_button = tk.Button(button_frame, 
                                text="立即清空文件",
                                font=('Microsoft YaHei', 12, 'bold'),
                                bg='#c0392b', fg='white',
                                relief='flat', padx=30, pady=10,
                                command=lambda: self.clear_all_files_and_close(completion_window))
        clear_button.pack(side='left')
    
    def clear_all_files_and_close(self, window):
        """清空所有文件并关闭对话框"""
        try:
            # 清空shuru文件
            self.clear_file()
            # 清空shuchu文件
            self.clear_shuchu_files()
            # 重置完成标志
            self.completion_dialog_shown = False
            # 关闭对话框
            window.destroy()
            # 显示成功提示
            messagebox.showinfo("成功", "所有文件已清空！")
        except Exception as e:
            messagebox.showerror("错误", f"清空文件时出错: {e}")

def main():
    """主函数"""
    root = tk.Tk()
    app = SequenceGenerator(root)
    root.mainloop()

if __name__ == "__main__":
    main()